<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { updateComboSourceDataApi, getComboSourceDataApi, putToYKZT } from "@/api/combo-source"
import { IGetComboSourceData } from "@/api/combo-source/types/combo-source"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"
import { Search, Refresh, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
defineOptions({
  name: "ComboSource"
})
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  name: "",
  shareId: "",
  token: "",
  channel: "",
  key: ""
})
const formRules: FormRules = reactive({
  shareId: [{ required: false, trigger: "blur", message: "请输入第三方ID" }],
  token: [{ required: false, trigger: "blur", message: "请输入第三方Token" }]
})

const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (currentUpdateId.value !== undefined) {
        updateComboSourceDataApi({
          id: currentUpdateId.value,
          name: formData.name,
          shareId: formData.shareId,
          token: formData.token,
          channel: formData.channel,
          key: formData.key
        }).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          getTableData()
        })
      }
    } else {
      return false
    }
  })
}
const resetForm = () => {
  currentUpdateId.value = undefined
  clearValidate()
  formData.name = ""
  formData.shareId = ""
  formData.token = ""
  formData.channel = ""
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: any) => {
  currentUpdateId.value = row.id
  formData.name = row.name
  formData.shareId = row.shareId
  formData.token = row.token
  formData.key = row.key
  formData.channel = row.channel

  dialogVisible.value = true
}
//#endregion

//#region 查
const tableData = ref<IGetComboSourceData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: ""
})
const getTableData = () => {
  loading.value = true
  getComboSourceDataApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    name: searchData.name || ""
  })
    .then((res) => {
      paginationData.total = res.data.total
      tableData.value = res.data.list
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleRefresh = () => {
  getTableData()
}
//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
// ** 清除规则报错信息
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const handleStatusChange = (row: any) => {
  putToYKZT({ id: row.id, share: row.share }).then((res: any) => {
    if (res.code == 200) {
      getTableData()
    }
  })
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="套餐来源">
          <el-input v-model.trim="searchData.name" clearable placeholder="请输入" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 中间部分 -->
    <!-- <el-card shadow="never" class="search-wrapper" style="display: none">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="套餐名">
          <el-input v-model="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card> -->
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <!-- <el-button type="primary" :icon="CirclePlus" @click="handleAdd">添加套餐</el-button> -->
          <!-- <el-button type="danger" :icon="Delete">批量删除</el-button> -->
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="name" label="套餐来源" align="center" />
          <el-table-column prop="name" label="是否同步到优卡掌厅-达讯订单列表" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.share"
                :active-value="1"
                :inactive-value="0"
                @click="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增套餐来源' : '修改套餐来源'"
      @close="resetForm"
      width="80%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="name" label="套餐来源">
          <el-input v-model="formData.name" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item prop="shareId" label="第三方ID">
          <el-input v-model="formData.shareId" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="token" label="第三方token">
          <el-input v-model="formData.token" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="token" label="Key">
          <el-input v-model="formData.key" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="channel" label="触点编码">
          <el-input v-model="formData.channel" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
